package nus.mtech.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * <p>
 * Title
 * </p>
 * <p>
 * Copyright (c) 2011 NUS ISS. All rights reserved.
 * </p>
 * 
 * @author Jiang Hao Min
 * @version 1.0
 * 
 * <p align='left'>
 * <table border='1' width='80%'>
 *   <tr>
 *     <th colspan='4'>Change History</th>
 *   </tr>
 *   <tr>
 *     <td><u>Version</u></td>
 *     <td><u>Name</u></td>
 *     <td><u>Date</u></td>
 *     <td><u>Remarks</u></td>
 *   </tr>
 *   <tr>
 *     <td>1.0</td>
 *     <td>Jiang Hao Min</td>
 *     <td>Mar 21, 2011</td>
 *     <td>Creation of the class.</td>
 *   </tr>
 * </table>
 * </p>
 */

public class DateUtil {
	public static String DATE_FORMAT = "dd/MM/yyyy";
	public static String DATE_TIME_FORMAT = "dd/MM/yyyy HH:mm:ss";

	public static boolean isValidDate(String date, String format) {
		if (StringUtil.isBlank(date) || StringUtil.isBlank(format)) {
			return false;
		}

		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Date testDate = null;

		try {
			testDate = sdf.parse(date);
		} catch (ParseException e) {
			return false;
		}
		if (!sdf.format(testDate).equals(date)) {
			return false;
		}
		return true;
	}

	public static String formatDate(Date date, String format) {
		if (date != null) {
			if (StringUtil.isBlank(format)) {
				format = DateUtil.DATE_FORMAT;
			}
			DateFormat df = DateFormat.getDateInstance();
			SimpleDateFormat sdf = (SimpleDateFormat) df;
			sdf.setLenient(false);
			sdf.applyPattern(format);
			return sdf.format(date);
		} else {
			return null;
		}
	}

	public static String formatDate(Date date) {
		return formatDate(date, DATE_FORMAT);
	}

	public static Date parseDate(String date, String format) {
		Date parsedDate = null;
		DateFormat df = DateFormat.getDateInstance();
		SimpleDateFormat sdf = (SimpleDateFormat) df;
		sdf.setLenient(false); // added for strict checking of date object
		sdf.applyPattern(format);
		try {
			if (!StringUtil.isBlank(date)) {
				parsedDate = sdf.parse(date);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return parsedDate;
	}

	public static Date addMonths(Date date, int amount) {
        return add(date, Calendar.MONTH, amount);
    }
	
	public static Date add(Date date, int calendarField, int amount) {
        if (date == null) {
            throw new IllegalArgumentException("The date must not be null");
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(calendarField, amount);
        return c.getTime();
    }
	
	public static boolean sameMonth(Date date1, Date date2) {
		if (date1.getYear() == date2.getYear())
			return date1.getMonth() == date2.getMonth();
		return false;
	}
}
